package com.zqwh.storemonitor.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.videogo.errorlayer.ErrorInfo;
import com.videogo.exception.BaseException;
import com.videogo.openapi.EZConstants;
import com.videogo.openapi.EZPlayer;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.openapi.bean.EZDeviceInfo;
import com.zqwh.storemonitor.R;
import com.zqwh.storemonitor.domain.Camera;
import com.zqwh.storemonitor.domain.Monitor;
import com.zqwh.storemonitor.domain.ShopBell;
import com.zqwh.storemonitor.ezviz.EZUtils;
import com.zqwh.storemonitor.model.WatcherModel;
import com.zqwh.yj.sdk.utils.LogUtils;
import com.zqwh.yj.sdk.utils.SharePreferencesUtils;
import com.zqwh.yj.sdk.utils.ToastUtils;
import com.zqwh.yj.sdk.utils.httpRequest.subscribers.NetCallback;
import com.zqwh.yj.sdk.widget.monindicator.MonIndicator;

import java.util.ArrayList;
import java.util.List;

import static android.support.v7.widget.RecyclerView.SCROLL_STATE_IDLE;
import static com.zqwh.storemonitor.BundleKey.KEY_CAMERA_SPAN_COUNT;
import static com.zqwh.storemonitor.BundleKey.KEY_POSITION;
import static com.zqwh.storemonitor.Config.CAMERA_SPAN_COUNT;
import static com.zqwh.storemonitor.StoreMonitorApplication.getOpenSDK;
import static com.zqwh.storemonitor.StoreMonitorApplication.sSelectedCamera;
import static com.zqwh.storemonitor.StoreMonitorApplication.sSelectedShop;
import static com.zqwh.storemonitor.activity.StoreListActivity.MSG_START_PLAY;
import static com.zqwh.storemonitor.activity.StoreListActivity.MSG_TRY_AGAIN;

public class CameraListActivity extends BaseActivity {
    private RecyclerView rvCameraList;

    private RelativeLayout rlMask;
    private RelativeLayout rlTalk;
    private ImageView imgCloseDialog;
    private TextView tvTalkTip;
    private MonIndicator miTalking;
    private RelativeLayout rlOperate;

    private CameraAdapter cameraAdapter;
    private List<Camera> cameraList;
    private ImageView imgVoiceSwitch;
    private ImageView imgLockSwitch;

    private Camera selectedCamera = null;
    private CameraAdapter.LocalViewHolder selectedHolder = null;
    private Integer selectedPosition = null;
    private WatcherModel watcherModel;

    private int currentFirstPosition = 0;
    private int currentLastPosition = 0;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_list);
        watcherModel = new WatcherModel(this);
        cameraList = new ArrayList<>();
        setView();
        initToolbar();
        initCameraList();
    }

    @Override
    protected void onResume() {
        super.onResume();

        startAllRealPlay();
    }

    private void setView() {
        rlMask = findViewById(R.id.rl_mask);
        rlTalk = findViewById(R.id.rl_talk);
        imgCloseDialog = findViewById(R.id.img_close_dialog);
        tvTalkTip = findViewById(R.id.tv_talk_tip);
        miTalking = findViewById(R.id.mi_talking);

        rlOperate = findViewById(R.id.rl_operate);
        imgVoiceSwitch = findViewById(R.id.img_voice_switch);
        imgLockSwitch = findViewById(R.id.img_lock_switch);

        rvCameraList = findViewById(R.id.rv_camera_list);
    }

    private void initToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.inflateMenu(R.menu.camera_menu);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (item.getItemId() == R.id.action_arrange_1){
                    SharePreferencesUtils.writeIntSharedPreferences(CameraListActivity.this, KEY_CAMERA_SPAN_COUNT, 1);
                    recreate();
                } else if (item.getItemId() == R.id.action_arrange_2){
                    SharePreferencesUtils.writeIntSharedPreferences(CameraListActivity.this, KEY_CAMERA_SPAN_COUNT, 2);
                    recreate();
                } else if (item.getItemId() == R.id.action_arrange_4){
                    SharePreferencesUtils.writeIntSharedPreferences(CameraListActivity.this, KEY_CAMERA_SPAN_COUNT, 4);
                    recreate();
                }
                return true;
            }
        });
    }

    private void initListView(){
        CAMERA_SPAN_COUNT = SharePreferencesUtils.readIntSharedPreferences(CameraListActivity.this, "CAMERA_SPAN_COUNT");
        if (CAMERA_SPAN_COUNT == 0){
            CAMERA_SPAN_COUNT = 1;
        }
        final GridLayoutManager layoutManager = new GridLayoutManager(this, CAMERA_SPAN_COUNT);
        rvCameraList.setLayoutManager(layoutManager);
        cameraAdapter = new CameraAdapter(this, cameraList);
        rvCameraList.setAdapter(cameraAdapter);
        cameraAdapter.setOnItemClickListener(new CameraAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(CameraAdapter.LocalViewHolder holder, int position, Camera camera) {
                if (selectedPosition != null && selectedPosition == position){
                    camera.setSelected(false);
                    camera.getMonitorPlayer().closeSound();
                    cameraAdapter.notifyItemChanged(position, holder.viewSelected);
                    hideBottomOperateBar();

                    selectedCamera = null;
                    selectedHolder = null;
                    selectedPosition = null;
                }else {
                    camera.setSelected(true);
                    if (selectedCamera == null){
                        cameraAdapter.notifyItemChanged(position, holder.viewSelected);
                    }else {
                        selectedCamera.setSelected(false);
                        selectedCamera.getMonitorPlayer().closeSound();
                        cameraAdapter.notifyItemChanged(position, holder.viewSelected);
                        cameraAdapter.notifyItemChanged(selectedPosition, selectedHolder.viewSelected);
                    }
                    selectedCamera = camera;
                    selectedHolder = holder;
                    selectedPosition = position;

                    selectedCamera.getMonitorPlayer().openSound();
                    showBottomOperateBar();
                }
            }

            @Override
            public void onDoubleItemClick(CameraAdapter.LocalViewHolder holder, int position, Camera camera) {
                sSelectedCamera = camera;
                startActivity(new Intent(CameraListActivity.this, CameraDetailActivity.class));
            }
        });

        imgVoiceSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(CameraListActivity.this,
                        Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(CameraListActivity.this,
                            new String[]{Manifest.permission.RECORD_AUDIO}, 0);
                    return;
                }
                selectedCamera.getMonitorPlayer().startVoiceTalk();
                showTalkDialog();
            }
        });

        imgLockSwitch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                watcherModel.setOutAllow(sSelectedShop.getDevSn(), !sSelectedShop.isOutAllow(), new NetCallback<ShopBell>() {
                    @Override
                    public void onSuccess(ShopBell myShop) {
                        sSelectedShop.setOutAllow(myShop.isOutAllow());
                        updateLockStatusUI();
                    }

                    @Override
                    public void onError(String msg) {
                        ToastUtils.showLongToast(CameraListActivity.this, "操作失败");
                    }
                });
            }
        });

        imgCloseDialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectedCamera.getMonitorPlayer().stopVoiceTalk();
                hideTalkDialog();
            }
        });

        rvCameraList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                if (newState == SCROLL_STATE_IDLE) {
                    int firstPosition = layoutManager.findFirstVisibleItemPosition();
                    int lastPosition = layoutManager.findLastVisibleItemPosition();

                    LogUtils.logout("currentFirstPosition="+currentFirstPosition);
                    LogUtils.logout("currentLastPosition  ="+currentLastPosition);

                    LogUtils.logout("newFirstPosition="+firstPosition);
                    LogUtils.logout("newLastPosition  ="+lastPosition);

                    for (int index = firstPosition; index <= lastPosition; index ++ ){
                        if (index < currentFirstPosition || index > currentLastPosition){
                            Message message = new Message();
                            message.what = MSG_START_PLAY;
                            Bundle bundle = new Bundle();
                            bundle.putInt(KEY_POSITION, index);
                            message.setData(bundle);
                            LogUtils.logout("send "+index);
                            handler.sendMessageDelayed(message, 50);
                        }
                    }

                    currentFirstPosition = firstPosition;
                    currentLastPosition = lastPosition;
                }

            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void updateLockStatusUI() {
        if (sSelectedShop.isOutAllow()) {
            imgLockSwitch.setImageDrawable(getDrawable(R.mipmap.lock_on));
        }else {
            imgLockSwitch.setImageDrawable(getDrawable(R.mipmap.lock_off));
        }
    }

    private void initCameraList() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    List<Monitor> monitorList = sSelectedShop.getMonitors();
                    if (monitorList != null && monitorList.size() > 0) {
                        for (Monitor monitor:monitorList){
                            EZDeviceInfo deviceInfo = getOpenSDK().getDeviceInfo(monitor.getMonitorSn());

                            for (int index = 0; index < deviceInfo.getCameraNum(); index ++){
                                EZCameraInfo cameraInfo = EZUtils.getCameraInfoFromDevice(deviceInfo, index);
                                EZPlayer player = getOpenSDK().createPlayer(cameraInfo.getDeviceSerial(), cameraInfo.getCameraNo());
                                Camera camera = new Camera();
                                camera.setIndex(index);
                                camera.setMonitorSn(monitor.getMonitorSn());
                                camera.setMonitorPlayer(player);
                                camera.setMonitorSoundOn(false);
                                camera.setMonitorVoiceOn(false);
                                camera.setSelected(false);
                                cameraList.add(camera);
                            }
                        }
                    }

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            initListView();
                            startAllRealPlay();
                        }
                    });
                } catch (BaseException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == MSG_START_PLAY) {
                int position = msg.getData().getInt("POSITION");
                startRealPlay(cameraList.get(position));
            }else if (msg.what == MSG_TRY_AGAIN){

            }
            return false;
        }
    });

    private void startAllRealPlay(){
        for (Camera camera: cameraList){
            Message message = new Message();
            message.what = MSG_START_PLAY;
            Bundle bundle = new Bundle();
            bundle.putInt(KEY_POSITION, camera.getIndex());
            message.setData(bundle);
            handler.sendMessageDelayed(message, 50);
        }
    }

    private void startRealPlay(Camera camera){
        if (camera.getMonitorSv() == null){
            return;
        }
        camera.getMonitorPlayer().setSurfaceHold(camera.getMonitorSv().getHolder());
        camera.getMonitorPlayer().setHandler(new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_SUCCESS:
                        startTalkSuccess();
                        break;
                    case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_STOP:
                        LogUtils.logout("MSG_REALPLAY_VOICETALK_STOP");
                        break;
                    case EZConstants.EZRealPlayConstants.MSG_REALPLAY_VOICETALK_FAIL:
                        ErrorInfo errorInfo = (ErrorInfo) msg.obj;
                        startTalkFail();
                        break;
                    case EZConstants.MSG_GOT_STREAM_TYPE:
                        LogUtils.logout("handleMessage -->" + "获取到当前取流类型");
                        break;
                    case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_SUCCESS:
                        //播放成功
                        LogUtils.logout("handleMessage -->" + "播放成功");
                        break;
                    case EZConstants.EZRealPlayConstants.MSG_REALPLAY_STOP_SUCCESS:
                        //播放成功
                        LogUtils.logout("handleMessage -->" + "停止成功");
                        break;
                    case EZConstants.EZRealPlayConstants.MSG_REALPLAY_PLAY_FAIL:
                        //播放失败,得到失败信息
                        ErrorInfo errorinfo = (ErrorInfo) msg.obj;
                        //得到播放失败错误码
                        int code = errorinfo.errorCode;
                        //得到播放失败模块错误码
                        String codeStr = errorinfo.moduleCode;
                        //得到播放失败描述
                        String description = errorinfo.description;
                        //得到播放失败解决方方案
                        String sulution = errorinfo.sulution;
                        LogUtils.logout("handleMessage -->播放失败,得到失败信息: " + errorinfo.toString());
                        break;
                    case EZConstants.MSG_VIDEO_SIZE_CHANGED:
                        //解析出视频画面分辨率回调
                        try {
                            String temp = (String) msg.obj;
                            String[] strings = temp.split(":");
                            int mVideoWidth = Integer.parseInt(strings[0]);
                            int mVideoHeight = Integer.parseInt(strings[1]);
                            //解析出视频分辨率
                            LogUtils.logout("handleMessage -->解析出视频分辨率: " + mVideoWidth + "," + mVideoHeight);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        }));
        camera.getMonitorPlayer().startRealPlay();
        camera.getMonitorPlayer().closeSound();
    }

    private void showTalkDialog() {
        rlMask.setVisibility(View.VISIBLE);
        rlTalk.setVisibility(View.VISIBLE);
        imgCloseDialog.setVisibility(View.VISIBLE);
        tvTalkTip.setVisibility(View.VISIBLE);
    }

    private void startTalkSuccess() {
        tvTalkTip.setVisibility(View.GONE);
        miTalking.setVisibility(View.VISIBLE);
    }

    private void startTalkFail() {
        tvTalkTip.setText("启动失败，点击重试");
    }

    private void hideTalkDialog() {
        rlMask.setVisibility(View.GONE);
        rlTalk.setVisibility(View.GONE);
        imgCloseDialog.setVisibility(View.GONE);
        tvTalkTip.setVisibility(View.GONE);
        miTalking.setVisibility(View.GONE);
    }

    private void showBottomOperateBar(){
        rlOperate.setVisibility(View.VISIBLE);
    }

    private void hideBottomOperateBar(){
        rlOperate.setVisibility(View.GONE);
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Camera camera : cameraList) {
            if (camera.getMonitorPlayer() != null){
                camera.getMonitorPlayer().release();
            }
        }
    }
}
